<template>
    <el-card class="w-full pt-[5px]">
        <el-radio-group v-model="planType" @change="getList(1)">
            <el-radio-button v-for="item in statisticsList" :key="item.value" :value="item.value">{{ item.name }}({{
            item.count
        }})</el-radio-button>
        </el-radio-group>
        <el-form :model="searchForm" class="mt-[20px]" label-width="110px">
            <el-row :gutter="20">
                <el-col :span="6">
                    <el-form-item label="成果名称" class="mb-[0px]">
                        <el-input v-model="searchForm.productName" clearable />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="完成人姓名" class="mb-[0px]">
                        <el-input v-model="searchForm.authorName" clearable />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="申请日期">
                        <!-- <el-date-picker v-model="searchForm.applyDate" type="date" format="YYYY/MM/DD"
                            value-format="YYYY-MM-DD" /> -->
                        <el-date-picker v-model="valueDate1" format="YYYY/MM/DD" value-format="YYYY-MM-DD"
                            type="daterange" range-separator="至" />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <div class="flex justify-end">
                        <el-button type="primary" @click="searchFormOpen = !searchFormOpen">更多
                            <el-icon color="#fff">
                                <CaretTop v-show="searchFormOpen" />
                                <CaretBottom v-show="!searchFormOpen" />
                            </el-icon>
                        </el-button>
                        <el-button type="primary" @click="queryMet">查询</el-button>
                        <el-button @click="reset">重置</el-button>
                    </div>
                </el-col>
            </el-row>
            <el-row :gutter="20" class="mt-[0px]" v-show="searchFormOpen">
                <el-col :span="6">
                    <el-form-item label="奖励状态" class="mb-[0px]">
                        <el-select v-model="searchForm.honorState">
                            <el-option v-for="item in hjztist" :key="item.code" :label="item.name" :value="item.code" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="所属单位">
                        <CustomTreeSelect placeholder="所属单位" v-model="searchForm.unitId" valueKey="codeColumn"
                            labelKey="valueColumn" :isFetch="false" :dataList="isKyms ? msDwArr : zcgsdwList" />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="学科名称">
                        <el-select v-model="searchForm.subjectId" clearable>
                            <el-option v-for="item in kjxkflList" :key="item.id" :label="item.label" :value="item.id" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="完成单位" class="mb-[0px]">
                        <el-input v-model="searchForm.completeUnit" clearable />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="成果形式" class="mb-[0px]">
                        <el-input v-model="searchForm.productMode" clearable />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="审核状态" class="mb-[0px]">
                        <!-- <el-select v-model="searchForm.checkstatus" clearable>
                            <el-option v-for="item in shztList" :key="item.code" :label="item.name"
                                :value="item.code" />
                        </el-select> -->
                        <CustomTreeSelect placeholder="审核状态" v-model="searchForm.checkstatus" valueKey="code"
                            labelKey="name" :isFetch="false" :dataList="shztList" />
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
    </el-card>
    <el-card class="w-full pt-[5px] mt-[10px]">
        <div class="mb-[20px]">
            <el-button type="primary" v-equalRole="['biz_kycgly']" @click="handleAdd">
                <el-icon class="mr-[5px]">
                    <Plus />
                </el-icon>
                新增
            </el-button>
            <el-button @click="handleDel">
                <el-icon>
                    <DeleteFilled />
                </el-icon>
                删除
            </el-button>
            <el-button @click="exportVisible = true">
                <svg-icon iconClass="export" class="mr-[5px]"></svg-icon>导出
            </el-button>
            <el-button @click="goBack">
                返回
            </el-button>
        </div>
        <el-table :data="tableData" class="w-full" @selection-change="handleSelectionChange" stripe>
            <el-table-column type="selection" width="55" :selectable="checkSelectable" />
            <el-table-column prop="productName" label="成果名称">
                <template #default="scope">
                    <el-link type="primary" @click="viewItem(scope.row)">{{ scope.row.productName }}</el-link>
                </template>
            </el-table-column>
            <el-table-column prop="inventorNames" label="所有完成人">
                <template #default="scope">
                    <span v-for="(item, index) in scope.row.authorList1" :key="item.id">
                        <el-link type="primary" v-if="item.id != '3'" @click="openpeopledetails(item)">{{
            item.name
        }}<span v-if="index + 1 != scope.row.authorList1.length">,</span></el-link>
                        <span type="primary" v-else>{{
            item.name
        }}<span v-if="index + 1 != scope.row.authorList1.length">,</span></span>
                    </span>
                </template>
            </el-table-column>
            <el-table-column prop="applyDate" label="申请日期" :formatter="dateFormatter2" />
            <el-table-column prop="honorState" label="获奖状态"> <template #default="scope">
                    <Feedback :id="scope.row.honorState" :list="hjztist">
                    </Feedback>
                </template>
            </el-table-column>
            <el-table-column prop="unitId" label="所属部门">
                <template #default="scope">
                    <Feedback :id="scope.row.unitId" :list="zcgsdwList" :mapping="['codeColumn', 'valueColumn']">
                    </Feedback>
                </template>
            </el-table-column>

            <el-table-column prop="selectExpert" label="已选专家" />
            <el-table-column prop="reviewMark" label="评审进度">
                <template #default="scope">
                    <el-progress :text-inside="true" :stroke-width="26"
                        :percentage="(Number(scope.row.submitNum) + Number(scope.row.noSubmitNum)) != 0 ? Number(scope.row.submitNum) / (Number(scope.row.submitNum) + Number(scope.row.noSubmitNum)) * 100 : 0" /></template>
            </el-table-column>
            <el-table-column prop="checkstatus" label="审核状态"> <template #default="scope">
                    <Feedback :id="scope.row.checkstatus" :list="shztList">
                    </Feedback>
                </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="300" align="center">
                <template #default="scope">
                    <el-button type="primary" v-equalRole="['biz_kycgly']" size="small" plain
                        @click="handleEdit(scope.row)">
                        编辑
                    </el-button>
                    <el-button type="primary" v-equalRole="['biz_kyms']" v-show="scope.row.checkstatus != '2'"
                        size="small" plain @click="handleEdit(scope.row)">
                        编辑
                    </el-button>
                    <el-button type="success" v-show="scope.row.isAuditor" size="small"
                        @click="handleCheck(scope.row.id, scope.row.processInstanceId)" plain>
                        审核
                    </el-button>
                    <el-button type="danger" size="small" v-equalRole="['biz_kycgly']"
                        v-show="(scope.row.checkstatus == '-1' || scope.row.checkstatus == '3') && checkSelectable(scope.row)"
                        plain @click="delHonor(scope.row)">删除</el-button>
                    <el-button type="danger" size="small" v-equalRole="['biz_kyms']"
                        v-show="(scope.row.checkstatus == '-1' || scope.row.checkstatus == '3') && checkSelectable(scope.row)"
                        plain @click="delHonor(scope.row)">删除</el-button>
                    <el-button type="primary"
                        v-show="scope.row.checkstatus == '2' && scope.row.honorState != '3' && route.query.isReview == '0'"
                        size="small" @click="registration(scope.row)" plain>
                        登记获奖
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="mt-[20px] flex justify-end">
            <pagination v-show="total > 0" :total="total" v-model:page="pageInfo.pageNum"
                v-model:limit="pageInfo.pageSize" @pagination="getList" />
        </div>
    </el-card>
    <detailEdit v-model="editModelVisible" ref="EditModalRef" :hjztList="hjztList" :hjjbList="hjjbList"
        :zcgsdwList="zcgsdwList" :sydwList="sydwList" :kjxkflList="kjxkflList" :xlList="xlList" :zcList="zcList"
        @callBack="callBackFun" />
    <detailView v-model="ViewdialogVisible" ref="viewModalRef" :hjztList="hjztList" :hjjbList="hjjbList"
        :zcgsdwList="zcgsdwList" :sydwList="sydwList" :kjxkflList="kjxkflList" :xlList="xlList" :zcList="zcList" />
    <exportModal v-model="exportVisible" :selectList="exportList" title="申报材料" @callBack="callBackMet" />
    <CheckModal v-model="CheckModalVisible" ref="checkModalRef" :hjztList="hjztList" :hjjbList="hjjbList"
        :zcgsdwList="zcgsdwList" :sydwList="sydwList" :kjxkflList="kjxkflList" :xlList="xlList" :zcList="zcList"
        @callBack="callBackFun" />
    <cgEditModal v-model="cgModelVisible" title="登记获奖" ref="cgEditModalRef" :hjjbList="hjjbList" :hjdjList="hjdjList"
        :hjnbList="hjnbList" :xmlyList="xmlyList" :xlList="xlList" :zcList="zcList" :zcgsdwList="zcgsdwList"
        :sydwList="sydwList" :kjxkflList="kjxkflList" :skxkflList="skxkflList" @callBack="cgcallBackFun" />
    <peopleDetails :activ="activ" :obj="obj" @close-dialog="activ = false"></peopleDetails>
</template>

<script setup>
import { onMounted } from 'vue';
import { getCategory } from "@/api/system/category"
import { useRouter, useRoute } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { gethonorApplyBookList, honorApplyBookDel, gethonorApplyBookInfo, updateHonorApplyBookHonorState, gethonorApplyBookListStatistics } from "@/api/achievement/cghj"
import detailEdit from "./detailEdit.vue";
import detailView from "./detailView.vue";
import useCategoryStore from "@/store/modules/category";
import exportModal from "@/components/export";
import { exportFile } from "@/api/fee/common.js";
import { downloadFile } from "@/utils/main";
import useUserStore from "@/store/modules/user";
import CustomTreeSelect from "@/views/project/components/CustomTreeSelect.vue";
import Cookies from 'js-cookie'
import CheckModal from "./CheckModal.vue";
import cgEditModal from "../hjcg/EditModal";
import peopleDetails from '@/components/peopleDetails/peopleDetails.vue'


const categoryStore = useCategoryStore();
const { hjjbList, hjztList, zcgsdwList, shztList, kjxkflList, xlList, zcList, hjztist, hjdjList, hjnbList, xmlyList, skxkflList,
    sydwList } = storeToRefs(categoryStore); // 解构状态
const { gethjjbList, gethjztList, getzcgsdwList, getshztList, getkjxkflList, getxlList, getzcList, gethjztist, gethjdjList, gethjnbList, getxmlyList, getskxkflList,
    getsydwList } = categoryStore; // 解构方法

const userStore = useUserStore();

const router = useRouter();
const route = useRoute();
const planType = ref("");
const searchFormOpen = ref(false);
const editModelVisible = ref(false);
const ViewdialogVisible = ref(false);
const exportVisible = ref(false);
const cgModelVisible = ref(false);
const CheckModalVisible = ref(false);

const checkModalRef = ref();
//点击审核
const handleCheck = (id, processId) => {
    gethonorApplyBookInfo(id).then((res) => {
        if (res.code == 200) {
            CheckModalVisible.value = true;
            checkModalRef.value.getRuleForm(res.data, processId);
        }
    });
};

const msDwArr = ref([])


const cgEditModalRef = ref()

const cgId = ref('')
//登记获奖
const registration = (i) => {
    cgId.value = i.id;
    let zcData = {
        honorSn: '',
        honorNumber: 1,
        name: '',
        productName: '',
        honorUnit: '',
        honorLevelId: "",
        honorGradeId: '',
        honorTypeId: '',
        honorDate: '',
        productMode: '',
        totalUnitNum: '',
        unitId: '',
        cooperationType: '1',
        honorFee: '',
        scale: null,
        completeUnit: '',
        unitOrderId: '',
        subjectClassId: '1',
        subjectId: '',
        projectSourceId: '',
        note: '',
        fileIds: '',
        honorAuthorVOs: []
    }
    gethonorApplyBookInfo(i.id).then(res => {
        if (res.code == 200) {
            zcData.name = route.query.honorName
            zcData.honorLevelId = route.query.honorLevel
            zcData.productName = res.data.productName
            zcData.productMode = res.data.productMode
            zcData.completeUnit = res.data.completeUnit
            zcData.unitId = res.data.unitId
            zcData.honorAuthorVOs = res.data.honorApplyBookMemberVOs

            cgModelVisible.value = true;
            cgEditModalRef.value.getRuleForm(zcData)
        }
    })

}
const searchForm = ref({
    applyInfoId: "",
    productName: "",
    authorName: "",
    applyDateStart: "",
    applyDateEnd: "",
    honorState: "",
    unitId: [], //所属单位
    checkstatus: [],
    productMode: "",
    completeUnit: "",
    subjectId: "",
});
const pageInfo = ref({
    pageNum: 1,
    pageSize: 10
})
const total = ref(0)
const tableData = ref([])

//点击新增
const handleAdd = () => {
    editModelVisible.value = true;
};
const EditModalRef = ref(null)
//点击编辑
const handleEdit = (i) => {
    gethonorApplyBookInfo(i.id).then(res => {
        if (res.code == 200) {
            editModelVisible.value = true;
            if (i.isAuditor) {
                EditModalRef.value.getRuleForm(res.data, i.taskId, i.isAuditor)
            } else {
                EditModalRef.value.getRuleForm(res.data)
            }

        }
    })
};


const viewModalRef = ref(null)
const viewItem = (i) => {
    gethonorApplyBookInfo(i.id).then(res => {
        if (res.code == 200) {
            ViewdialogVisible.value = true;
            viewModalRef.value.getRuleForm(res.data, i.processInstanceId)
        }
    })
};
const multipleSelection = ref([])
const handleSelectionChange = (val) => {
    multipleSelection.value = val
}
//点击删除
const handleDel = () => {
    if (multipleSelection.value.length == 0) {
        ElMessage.warning("请选择要删除的数据")
        return;

    } else {
        ElMessageBox.confirm("是否确认删除？", "提示", {
            type: "warning",
        }).then(() => {
            let ids = multipleSelection.value.map(item => item.id)
            ids = ids.join(',')
            honorApplyBookDel(ids).then(res => {
                if (res.code == 200) {
                    getList()
                    ElMessage.success('删除成功')
                }
            })
        });
    }

};
const initList = () => {
    getList()

}
const reset = () => {
    searchForm.value = {
        applyInfoId: "",
        productName: "",
        authorName: "",
        applyDateStart: "",
        applyDateEnd: "",
        honorState: "",
        unitId: [], //所属单位
        checkstatus: [],
        productMode: "",
        completeUnit: "",
        subjectId: "",
    }
    valueDate1.value = ''
    searchForm.value.applyInfoId = route.query.id
}

const valueDate1 = ref('')
const getList = async (i) => {
    gethonorApplyBookListStatisticsMet()
    if (i == 1) {
        pageInfo.value.pageNum = 1
    }
    if (valueDate1.value && valueDate1.value.length) {
        searchForm.value.applyDateStart = valueDate1.value[0]
        searchForm.value.applyDateEnd = valueDate1.value[1]
    } else {
        searchForm.value.applyDateStart = ''
        searchForm.value.applyDateEnd = ''
    }
    let parms = {
        ...searchForm.value,
        ...pageInfo.value,
        checkstatusGroup: planType.value,
    }
    parms.unitId = searchForm.value.unitId.join(",")
    parms.checkstatus = searchForm.value.checkstatus.join(',')
    // if (isKyms.value && (parms.unitId == '' || parms.unitId == null || parms.unitId == undefined || parms.unitId == [])) {
    //     parms.unitId = msDwArr.value.map(item => item.codeColumn).join(",")
    // }
    let res = await gethonorApplyBookList(parms)
    if (res.code == 200) {
        tableData.value = res.rows
        total.value = res.total
        tableData.value.forEach(item => {
            if (item.authornames && item.authorpids) {
                let zcNameArr = item.authornames.split(',')
                let zcNameArr1 = item.authorpids.split(',')
                let zcNameArr2 = zcNameArr.map((val, index) => {
                    return {
                        name: val,
                        id: zcNameArr1[index]
                    }
                })
                Reflect.set(item, 'authorList1', zcNameArr2)
            }
        })
    }
}
const callBackFun = () => {
    getList()
}
const cgcallBackFun = (i) => {
    if (i != '2') {
        updateHonorApplyBookHonorState({ id: cgId.value, honorState: '3' }).then(res => {
            getList()
        })
    }
}
const delHonor = (i) => {
    ElMessageBox.confirm(
        '确认！删除这条数据?',
        '提醒',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            honorApplyBookDel(i.id).then(res => {
                if (res.code == 200) {
                    getList()
                    ElMessage.success('删除成功')
                }
            })


        })
        .catch(() => {

        })

}

const exportList = [{
    lable: '奖励名称',
    value: 'honorName',
    isSelect: true,
}, {
    lable: '奖励级别',
    value: 'honorLevel',
    isSelect: false,
}, {
    lable: '成果名称',
    value: 'productName',
    isSelect: true,
}, {
    lable: '申请日期',
    value: 'applyDate',
    isSelect: true,
}, {
    lable: '所属单位',
    value: 'unitName',
    isSelect: true,
}, {
    lable: '所有完成人',
    value: 'authornames',
    isSelect: true,
}, {
    lable: '完成单位',
    value: 'completeUnit',
    isSelect: false,
}, {
    lable: '成果形式',
    value: 'productMode',
    isSelect: false,
}, {
    lable: '备注',
    value: 'note',
    isSelect: false,
}, {
    lable: '评审分值',
    value: 'reviewMark',
    isSelect: false,
}]

const callBackMet = (i) => {
    if (valueDate1.value && valueDate1.value.length) {
        searchForm.value.applyDateStart = valueDate1.value[0]
        searchForm.value.applyDateEnd = valueDate1.value[1]
    } else {
        searchForm.value.applyDateStart = ''
        searchForm.value.applyDateEnd = ''
    }
    let parms = {
        applyInfoId: route.query.id,
        selectedColumns: i.map(item => item.prop),
        ...searchForm.value,
        checkstatusGroup: planType.value,
    }
    exportFile('/achievement/honorApplyBook/export', parms).then(res => {
        downloadFile(res, `申报材料清单_${new Date().getTime()}.xlsx`);
    })
}


const isKyms = ref(false)

const goBack = () => {
    router.back()

}

const statisticsList = ref([{
    name: "全部",
    value: '',
    count: 0
},
{
    name: "审批通过",
    value: '2',
    count: 0
},
{
    name: "审批不通过",
    value: '3',
    count: 0
},
{
    name: "审批中",
    value: '1',
    count: 0
}])

const gethonorApplyBookListStatisticsMet = async () => {
    if (valueDate1.value && valueDate1.value.length) {
        searchForm.value.applyDateStart = valueDate1.value[0]
        searchForm.value.applyDateEnd = valueDate1.value[1]
    } else {
        searchForm.value.applyDateStart = ''
        searchForm.value.applyDateEnd = ''
    }
    let parms = {
        ...searchForm.value,
    };
    parms.unitId = searchForm.value.unitId.join(",")
    parms.checkstatus = searchForm.value.checkstatus.join(',')
    let res = await gethonorApplyBookListStatistics(parms);
    if (res.code == 200) {
        statisticsList.value.forEach(item => {
            if (item.name != '全部') {
                let hasStatis = res.data.filter(item1 => {
                    return item1.checkstatus == item.value
                })
                console.log(hasStatis);
                hasStatis && hasStatis.length ? item.count = hasStatis[0].count : item.count = 0
            }


        })
        let allNum = 0
        res.data.forEach(item => {
            allNum += item.count
        })
        statisticsList.value[0].count = allNum
    }
};

const queryMet = () => {
    getList(1)
}


///查看详情
const activ = ref(false)
const obj = ref('')
const openpeopledetails = function (row) {
    console.log(row)
    obj.value = row.id
    activ.value = true
}


const checkSelectable = (row, index) => {
    return row.checkstatus != '1';
}




onMounted(() => {
    if (Cookies.get("role-key") == 'biz_kyms') {
        isKyms.value = true
    } else {
        isKyms.value = false
    }
    if (!hjjbList.value.length) {
        gethjjbList()
    }
    if (!hjztList.value.length) {
        gethjztList()
    }



    if (!shztList.value.length) {
        getshztList()
    }
    if (!kjxkflList.value.length) {
        getkjxkflList()
    }
    if (!xlList.value.length) {
        getxlList()
    }
    if (!zcList.value.length) {
        getzcList()
    }
    if (!hjztist.value.length) {
        gethjztist()
    }
    if (!hjdjList.value.length) {
        gethjdjList()
    }
    if (!hjnbList.value.length) {
        gethjnbList()
    }
    if (!xmlyList.value.length) {
        getxmlyList()
    }
    if (!skxkflList.value.length) {
        getskxkflList()
    }

    searchForm.value.applyInfoId = route.query.id
    // if (isKyms.value) {
    //     if (!zcgsdwList.value.length) {
    //         getzcgsdwList().then(res => {
    //             if (res.code == 200) {
    //                 msDwArr.value = []
    //                 let msdwArr = userStore.unitAdminScopeReal.split(',')
    //                 res.data.forEach(item => {
    //                     if (msdwArr.includes(item.codeColumn)) {
    //                         msDwArr.value.push(item)
    //                     }
    //                 })
    //                 initList()
    //             }
    //         })
    //     } else {
    //         msDwArr.value = []
    //         let msdwArr = userStore.unitAdminScopeReal.split(',')
    //         zcgsdwList.value.forEach(item => {
    //             if (msdwArr.includes(item.codeColumn)) {
    //                 msDwArr.value.push(item)
    //             }
    //         })
    //         initList()
    //     }
    // } else {

    // }

    if (!zcgsdwList.value.length) {
        getzcgsdwList()
    }
    if (!sydwList.value.length) {
        getsydwList();
    }


    initList()

});
</script>

<style scoped lang="scss"></style>